package com.smile.spring;

import com.smile.spring.service.StringToUserPropertyEditor;
import com.smile.spring.service.User;
import com.smile.spring.service.UserService;
import com.smile.spring.service.UserService1;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.MessageSource;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.support.ResourceBundleMessageSource;

import java.beans.PropertyEditor;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/12/11 16:38
 */
@ComponentScan(value = "com.smile.spring",
        excludeFilters = {@ComponentScan.Filter(
                type = FilterType.ASSIGNABLE_TYPE,
                classes = UserService1.class)})
public class AppConfig {

    @Bean
    public UserService userService(){
        return new UserService();
    }


    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }

    @Bean
    public ApplicationListener<PayloadApplicationEvent> applicationListener() {
        return new ApplicationListener<PayloadApplicationEvent>() {
            @Override
            public void onApplicationEvent(PayloadApplicationEvent payloadApplicationEvent) {
                System.out.println(payloadApplicationEvent.getPayload());
            }
        };
    }


    @Bean
    public CustomEditorConfigurer customEditorConfigurer() {
        CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
        Map<Class<?>, Class<? extends PropertyEditor>> propertyEditorMap = new HashMap<>();

        // 表示StringToUserPropertyEditor可以将String转化成User类型，在Spring源码中，如果发现当前对象是String，而需要的类型是User，就会使用该PropertyEditor来做类型转化
        propertyEditorMap.put(User.class, StringToUserPropertyEditor.class);
        customEditorConfigurer.setCustomEditors(propertyEditorMap);
        return customEditorConfigurer;
    }

}
